<?php

namespace App\Http\Controllers\Wechat\Plugins;

use Laravel\Lumen\Routing\Controller as BaseController;
use App\Http\Controllers\Wechat\Messages;
use Xu42\DlpuNetwork\DlpuNetwork;
use Illuminate\Support\Facades\DB;

class Network extends BaseController
{

    public static function config($message)
    {
        $user = self::isRegisterByOpenid($message->FromUserName);

        if (!$user) {
            return Messages\Text::registerNetwork($message);
        }

        $dlpuNetwork = new DlpuNetwork($user->username, base64_decode($user->password));

        $config = $dlpuNetwork->getConfig();

        return Messages\Text::networkConfig($config);
    }


    /**
     * 是否已注册
     * @param $username
     * @return bool
     */
    public static function isRegister($username)
    {
        $user = DB::table('networkusers')->where('username', $username)->first();

        return $user ? $user : false;
    }

    /**
     * 是否已注册
     * @param $openid
     * @return bool
     */
    public static function isRegisterByOpenid($openid)
    {
        $user = DB::table('networkusers')->where('openid', $openid)->first();

        return $user ? $user : false;
    }

    /**
     * 学号密码是否正确
     * @param $username     String 学号
     * @param $password     String 密码
     * @return bool
     */
    public static function isValid($username, $password)
    {
        $dlpuNetwork = new DlpuNetwork($username, $password);

        $cookie = $dlpuNetwork->getCookie();

        return $cookie ? $cookie : false;
    }

    /**
     * 用户绑定或更新绑定信息
     * @param $isRegister   boolean 是否已绑定
     * @param $username
     * @param $password
     * @param $openid
     * @param $mobile
     * @return string
     */
    public static function saveOrUpdate($isRegister, $username, $realname, $password, $openid, $mobile)
    {
        if ($isRegister) {  // 已注册, 更新注册信息
            DB::table('networkusers')->where('id', $isRegister->id)->update([
                'realname'   => $realname,
                'password'   => base64_encode($password),
                'mobile'     => $mobile,
                'openid'     => $openid,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            $result = '更新绑定成功';
        } else {  // 未注册, 添加注册信息
            DB::table('networkusers')->insert([
                'username'   => $username,
                'realname'   => $realname,
                'password'   => base64_encode($password),
                'mobile'     => $mobile,
                'openid'     => $openid,
                'created_at' => date('Y-m-d H:i:s')
            ]);
            $result = '绑定成功';
        }

        return $result;
    }

}